# -*- coding: utf-8 -*-
import logging
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from app.models import AmazonStore
from app.services.amazon_sp_auth_service import AmazonAuthService # type: ignore

logger = logging.getLogger(__name__)

@login_required
@require_http_methods(["GET"])
def amazon_authorize_view(request):
    """Amazon授权视图 - 参考朋友代码的amazon_authorize_view"""
    try:
        # 获取参数
        store_id = request.GET.get('store_id')
        selling_partner_id = request.GET.get('selling_partner_id')
        
        if not store_id and not selling_partner_id:
            return HttpResponse("缺少store_id或selling_partner_id参数", status=400)
        
        # 如果提供了selling_partner_id，查找对应的店铺
        if selling_partner_id and not store_id:
            store = AmazonStore.objects.filter(seller_id=selling_partner_id).first()
            if not store:
                return HttpResponse(f"未找到selling_partner_id为{selling_partner_id}的店铺", status=404)
            store_id = store.id
        
        # 生成授权URL
        auth_service = AmazonAuthService()
        auth_url, state = auth_service.generate_auth_url(store_id)
        
        logger.info(f"重定向到Amazon授权页面 - Store: {store_id}, URL: {auth_url}")
        
        # 重定向到Amazon授权页面
        return HttpResponseRedirect(auth_url)
        
    except Exception as e:
        logger.error(f"Amazon授权失败: {str(e)}")
        return HttpResponse(f"授权失败: {str(e)}", status=500)

@csrf_exempt
@require_http_methods(["GET", "POST"])
def amazon_callback_view(request):
    """Amazon授权回调视图 - 参考朋友代码的amazon_codeback_view"""
    try:
        # 获取回调参数
        selling_partner_id = request.GET.get('selling_partner_id')
        spapi_oauth_code = request.GET.get('spapi_oauth_code')
        state = request.GET.get('state')
        error = request.GET.get('error')
        error_description = request.GET.get('error_description')
        
        logger.info(f"收到Amazon授权回调 - SellingPartnerId: {selling_partner_id}, Code: {spapi_oauth_code[:10] if spapi_oauth_code else None}...")
        
        # 检查是否有错误
        if error:
            error_msg = f"Amazon授权错误: {error}"
            if error_description:
                error_msg += f" - {error_description}"
            
            logger.error(f"{error_msg}, selling_partner_id: {selling_partner_id}")
            
            return render(request, 'amazon_auth/callback_error.html', {
                'error': error_msg,
                'back_url': reverse('admin:app_amazonstore_changelist')
            })
        
        # 检查必需参数
        if not spapi_oauth_code:
            error_msg = "缺少spapi_oauth_code参数"
            logger.error(error_msg)
            return render(request, 'amazon_auth/callback_error.html', {
                'error': error_msg,
                'back_url': reverse('admin:app_amazonstore_changelist')
            })
        
        if not selling_partner_id:
            error_msg = "缺少selling_partner_id参数"
            logger.error(error_msg)
            return render(request, 'amazon_auth/callback_error.html', {
                'error': error_msg,
                'back_url': reverse('admin:app_amazonstore_changelist')
            })
        
        # 处理授权回调
        auth_service = AmazonAuthService()
        result = auth_service.handle_callback(selling_partner_id, spapi_oauth_code, state)
        
        if result['success']:
            logger.info(f"Amazon授权成功 - Store: {result['store'].id}")
            return render(request, 'amazon_auth/callback_success.html', {
                'store': result['store'],
                'message': result['message'],
                'redirect_url': reverse('admin:app_amazonstore_changelist')
            })
        else:
            logger.error(f"Amazon授权失败: {result['error']}")
            return render(request, 'amazon_auth/callback_error.html', {
                'error': result['error'],
                'back_url': reverse('admin:app_amazonstore_changelist')
            })
    
    except Exception as e:
        error_msg = f"授权回调处理异常: {str(e)}"
        logger.error(error_msg)
        return render(request, 'amazon_auth/callback_error.html', {
            'error': error_msg,
            'back_url': reverse('admin:app_amazonstore_changelist')
        })

@login_required
@require_http_methods(["POST"])
def amazon_refresh_token_view(request, store_id):
    """刷新Amazon Token"""
    try:
        store = get_object_or_404(AmazonStore, id=store_id)
        auth_service = AmazonAuthService()
        
        success = auth_service.refresh_token(store)
        
        if success:
            return JsonResponse({
                'success': True,
                'message': f'店铺 {store.store_name} Token刷新成功'
            })
        else:
            return JsonResponse({
                'success': False,
                'error': 'Token刷新失败'
            })
            
    except Exception as e:
        logger.error(f"刷新Token失败: {str(e)}")
        return JsonResponse({
            'success': False,
            'error': f'Token刷新失败: {str(e)}'
        })

@login_required
def amazon_auth_status_view(request, store_id):
    """查看Amazon授权状态"""
    try:
        store = get_object_or_404(AmazonStore, id=store_id)
        
        context = {
            'store': store,
            'auth_url': reverse('amazon_authorize', kwargs={'store_id': store_id}),
            'refresh_url': reverse('amazon_refresh_token', kwargs={'store_id': store_id}),
        }
        
        return render(request, 'amazon_auth/auth_status.html', context)
        
    except Exception as e:
        messages.error(request, f'获取授权状态失败: {str(e)}')
        return redirect('admin:app_amazonstore_changelist')